
#include <QFileDialog>
#include <QFileInfo>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include <QGridLayout>
#include <QMessageBox>

#include "config.h"
#include <material_editor/textureeditor.h>
#include <session.h>

#include <gfx/itexture.h>

TextureEditor::TextureEditor(Texture* texture, QWidget *parent)
  : BaseMaterialEditorWidget(parent)
  , _scene(0)
  , _pixmapItem(0)
  , _groupView(0)
{
  _gui.setupUi (this);
  _groupView = new GroupTreeItemView(this);
  QGridLayout* layout = new QGridLayout(_gui.widgetGroupView);
  layout->setContentsMargins(QMargins (0, 0, 0, 0));
  layout->addWidget (_groupView, 0, 0);
  setBackgroundRole(QPalette::Window);

  _scene = new QGraphicsScene(this);
  _gui.graphicsView->setScene(_scene);
  _pixmapItem = new QGraphicsPixmapItem ();
  _scene->addItem(_pixmapItem);



  SetTexture (texture);
}


void TextureEditor::SetTexture(Texture *texture)
{
  _texture = texture;
  _groupView->SetGroupTreeItem(&texture->GetCategory());
  SetItem(texture);

  UpdateGUI ();
  SetDirty (false);
}

Texture* TextureEditor::GetTexture () 
{
  return _texture;
}

void TextureEditor::UpdateGUI()
{
  if (_texture)
    {
      _gui.lineEditFilename->setText(_texture->GetFilename());
      _gui.comboBoxWrap->setCurrentIndex(_texture->GetWrap());
      _gui.comboBoxFilter->setCurrentIndex(_texture->GetFilter());
			_gui.comboBoxMipMap->setCurrentIndex(_texture->GetMipMap ());
      _gui.comboBoxAnisotrophy->setCurrentIndex(_texture->GetAnisotropy());
    }
  TextureChanged();

}

void TextureEditor::Save()
{
  if (_texture)
    {
			Session::Get ()->MakeGLContextCurrent ();
			_texture->GetTexture ()->Bind ();
      _texture->SetFilename(_gui.lineEditFilename->text());
      _texture->SetWrap(_gui.comboBoxWrap->currentIndex());
      _texture->SetFilter(_gui.comboBoxFilter->currentIndex());
      _texture->SetAnisotropy(_gui.comboBoxAnisotrophy->currentIndex());
			_texture->SetMipMap (_gui.comboBoxMipMap->currentIndex ());
      _texture->Save();
      _texture->UpdateData();
    }

  SetDirty(false);
}

void TextureEditor::TextureChanged()
{
  const QString& basePath = Session::Get()->GetProjectFolder();

  QString filename = basePath + "/" + _gui.lineEditFilename->text();

  QPixmap pm;
  if (!pm.load (filename))
    {
      printf ("Could not load pixmap: %s\n", (const char*)filename.toAscii());
      fflush (stdout);
    }
  _pixmapItem->setPixmap(pm);
  if (pm.isNull())
    {
      printf ("Pixmap is null: %s\n", (const char*)filename.toAscii());
      fflush(stdout);
      return;
    }
  _pixmapItem->setOffset(0.0f, 0.0f);
  _pixmapItem->update();

}


void TextureEditor::on_pushButtonBrowse_clicked()
{
  QString filename = QFileDialog::getOpenFileName(this, tr("Open Imagefile"),
                                                  Session::Get()->GetProjectFolder() + "/textures/",
                                                  tr("Images (*.png *.xpm *.jpg *.tga *.dds)"));
  if (filename.isNull())
    {
      return;
    }

  const QString& basePath = Session::Get()->GetProjectFolder();
  if(!filename.contains(basePath, Qt::CaseInsensitive))
    {
      QMessageBox::StandardButton button =
          QMessageBox::question(this,
                                CE_TOOL_NAME,
                                "The file you were trying to add does not belong to the\n"
                                "projectfolder. Do you want to copy the selected file\n"
                                "into the texturesfolder within the projectfolder?",
                                QMessageBox::Yes | QMessageBox::No,
                                QMessageBox::Yes);
      if (button == QMessageBox::No)
        {
          _gui.lineEditFilename->setText("");
          TextureChanged ();
          return;
        }

      QFileInfo info (filename);
      QFile::copy(filename, basePath + "/textures/" + info.fileName());
      filename = "textures/" + info.fileName();
    }
  else
    {
      filename.replace(basePath + "/", "", Qt::CaseInsensitive);
    }

  _gui.lineEditFilename->setText(filename);
  TextureChanged();

}


void TextureEditor::on_comboBoxFilter_currentIndexChanged (int index)
{
	_gui.labelAnisotrophy->setEnabled(
		index == Texture::Filter_Anisotropic ||
		index == Texture::Filter_Default
		);
  _gui.comboBoxAnisotrophy->setEnabled(
		index == Texture::Filter_Anisotropic ||
		index == Texture::Filter_Default
		);
  SetDirty(true);
}

void TextureEditor::on_comboBoxWrap_currentIndexChanged (int index)
{
  SetDirty (true);
}

void TextureEditor::on_lineEditFilename_textChanged (const QString& texture)
{
  SetDirty(true);
}


void TextureEditor::on_comboBoxAnisotrophy_currentIndexChanged (int index)
{
  SetDirty (true);
}

void TextureEditor::on_comboBoxMipMap_currentIndexChanged (int index)
{
	SetDirty (true);
}

QString TextureEditor::GetTypeName ()
{
  return QString ("Texture");
}

QString TextureEditor::GetUnsaveMessage ()
{
  return QString ("Texture '%1' has unsaved changes. Save changes bevor close?").arg(GetName());
}
